#ifndef __PLATFORM_CONFIG_H__
#define __PLATFORM_CONFIG_H__
#include <pthread.h>
#include "list.h"
typedef unsigned char u8;
typedef unsigned int u32;
typedef unsigned short u16;
typedef int int32_t;
typedef unsigned int uint32_t;
typedef unsigned short uint16_t;
#define sizeof_arry(x) (sizeof(x)/sizeof(x[0]))
#define READ_BUF_LEN 1024
#define ULTRA_PATH "/dev/ultra_tvin_ctl"
#define PRIVATE_PAR "/dev/block/mmcblk0p13"
#define EX_PRIVATE_PAR "SystemConfig.txt"
//#define PRIVATE_PAR "/mnt/private/gprs.bin"
#define OFFLINE_DATA_GPS_PATH "/data/local/tmp/offline_data_gps.bin"
#define OFFLINE_DATA_GPS_AREA_PATH "/data/local/tmp/offline_data_gps_area.bin"
#define OFFLINE_DATA_MUSHU_PATH "/data/local/tmp/offline_data_mushu.bin"
#define OFFLINE_DATA_DEPTH_PATH "/data/local/tmp/offline_data_depth.bin"
#define Usart1_Printf(a, b) LOGE("%s", a)
#define BUFFER_SIZE 8*1024
#define TVIN_PATH "/sys/class/gpio_sw/PH13/data"
#define GPRS_BIN_LEN 4096
#define LED_PATH  "/dev/tm1818_disp"
#define GPIO_PATH  "/dev/gpio_ctl"
#define CHANLIANG_MUSHU_DATA_LEN 1500
#define MU_CHAN_OFFLINE_LEN (CHANLIANG_MUSHU_DATA_LEN*57+64)
#define GPS_DATA_BUF "$GPRMC,064916.00,V,,,,,,,300316,,,N*76" //just example data
#define SHUTDOWN_SYSTEM_CMD "system/bin/svc power reboot"
#define FUNCTION_KEY_GPIO "/sys/class/gpio_sw/PH18/data"
#define ALARM_GPIO "/sys/class/gpio_sw/PE5/data"
#define BUTTON_LED_GPIO "/sys/class/gpio_sw/PE6/data"
#define ALIGN_2B(x) (((x) + (1)) & ~(1))
#define PASSWD "LeiMingDianZiShenGengJi"
#define SEC_DIFF(o, n) ((n.tv_sec-o.tv_sec) + (n.tv_usec-o.tv_usec)/1000000)
#define GPS_MAX_DATA  50000
#define FUNC_KEY_ON_VAL  0
#define FUNC_KEY_OFF_VAL  1
#define PI 3.1415926535897932384626433832795
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define LOG_TXT_PATH "/storage/card/log.txt" 
#define AUTO_CALC_AREA (1<<15)
#define MANUAL_CALC_AREA 0
#define GPS_DATA_LOG_PATH "/data/local/tmp/gpsData.txt"
#define GPS_AREA_DATA_LOG_PATH "/data/local/tmp/gpsAreaData.txt"
#define MAX_SELECT_TIME 5000000
#define POWER_DETECT_PATH "/dev/power_detect"
#define I2C1 1
#define I2C3 3
#define LED_ERROR (0xffff)
#define LED_BLACK (0xfffe)
#define LED_GPS_ERROR 0xfffd
#define LED_ULTRA_ERROR 0xfffc
#define LED_TEST (0xfffb)

typedef struct {
    double x;
    double y;
    double bearing;
    int valid;
    int depth;
}stru_GPSPOINT;

typedef struct {
	double x_max;
	double y_max;
	double x_min;
	double y_min;
	double length_x;
	double length_y;
}stru_peakPoint;

typedef struct {
    struct list_head list;
    void *data;
    unsigned int len;
} OFFLINE_DATA_LIST;

enum SERVER_REQUET_CMD {
    SERVER_NONE = 0,
    SERVER_TAKE_PICTURE = 1,
    SERVER_READ_DEVICE = 2,
};

enum POWER_IRQ_STATE {
    POWER_INIT = 0,
    POWER_ON = 1,
    POWER_OFF = 2,
};

extern int socket_cli;
extern int send_data_error_count;
extern volatile int power_irq_state;
extern int led_angle_ajust_mode;
extern enum SERVER_REQUET_CMD server_request_cmd;
extern struct list_head mushu_data_head, gps_data_head, depth_data_head, gps_area_data_head;
extern pthread_mutex_t mutex_list;
extern volatile int flag_login, flag_newIp;
extern unsigned int app_version;
extern int gps_error;
static int ultra_error_flag;
extern unsigned int offline_gps_count;
extern unsigned int plough_state;

#pragma pack(1)
typedef struct
{
    long long magic;
    long long app_version; //开机时候bootloader中读取
    char LocalPhoneNum1[20];//手机号码 中交使用
    char terminalID[20];//本机号码
    char CarNumber[20];
    char CarNumber_utf8[20];
    char IP[30]; //
    unsigned short port;
    char code_jianquan[11];
    int depth;
    int ref_depth;
    float machine_width;
    int angle;
    int a_sensor_height;
	int angle_b;
	int a_sensor_height_b;
	int sensor_model; //传感器模式：1表示读取0x50，2表示读取0x51，3表示两个都读取
	int plough_model; //犁距传感器，0表示不使用，1表示使用。如=1，读取不到ID则不上传作业面积
	char plough_care_id[20];
    char md5[33];
} SysInf;
#pragma pack()
// 短消息参数结构，编码/解码共用
// 其中，字符串以''\0''结尾
typedef struct  SM_PARAM
{
    char SCA[16];   // 短消息服务中心号码(SMSC地址)
    char TPA[16];   // 目标号码或回复号码(TP-DA或TP-RA)
    unsigned char TP_PID;  // 用户信息协议标识(TP-PID)
    unsigned char TP_DCS;  // 用户信息编码方式(TP-DCS)
    char TP_SCTS[16];  // 服务时间戳字符串(TP_SCTS), 接收时用到
    char TP_UD[161]; // 原始用户信息(编码前或解码后的TP-UD)
    int index;   // 短消息序号，在读取时用到
}CMGStruct;

struct ring_buffer
{
    void         *buffer;     //缓冲区
    uint32_t     size;       //大小
    uint32_t     in;         //入口位置
    uint32_t       out;        //出口位置
    pthread_mutex_t *f_lock;    //互斥锁
};

#define SysInfLength  sizeof(SysInf)
extern double CalAreaInManual(stru_GPSPOINT gpsPoints[], unsigned int gpsIndex, stru_GPSPOINT planarPoints[], unsigned int width);
extern double getAreaOfMoving(stru_GPSPOINT planePoint[], unsigned int planePointIndex, unsigned int width);
extern long long led_encode(int disp);
extern int gps_factory_test(void);
extern void *mcu_communication(void *);
extern __s32 at24c16_write( __u32 twi_id, __u32 offset, __u32 len, __u8 *buf);
extern __s32 at24c16_read( __u32 twi_id, __u32 offset, __u32 len, __u8 *buf);
extern int OfflineBlockClear(char *path);
extern int systemCmd(char* path);
extern int extract_update_package(char *path);
extern int Compute_buf_md5(const char *src, char *md5_str, unsigned int len);
extern void system_offline();
extern void add_offline_data_list(struct list_head *head, void *data, unsigned int len);
extern void del_offline_data_list(OFFLINE_DATA_LIST *list);
extern int power_detect_signal(void);
extern void UTC2China(u8* pdata);
extern double gps_speed;
extern double gps_bearing;
extern int gps_year;
extern int gps_mon;
extern int gps_day;
extern int gps_hour;
extern int gps_min;
extern int gps_sec;
extern double cur_lat, cur_lon, cur_altitude;
extern int disp_set_para;
extern u32 RecodeCnter;
extern double g_currentAngle, g_currentAngle_b;

extern long currentTimeInSec();
extern void check_server_parameter(const char *p);
extern int UTF8toUnicode(unsigned char *ch, int *unicode);
extern void reinitSysPara();
extern void *listenWifiAp(void * arg);
extern void closeUltraUart(void);
extern int openUltraUart(char *path, int flags);
extern void *readUltraUart(void *arg);
extern int systemCmd(char* path);
extern int NetIsOk(char *addr);
extern double getAutoDistance(int harvesterState, int clean_all_data);
extern void stopAutoArea();
extern double CalAreaProcess(int *gps_valid_len);
extern void autoCalArea(int distance, struct timeval *start_time);
extern int Compute_file_md5(const char *file_path, char *md5_str);
extern int remount_system(unsigned long flags);
extern void split(char *buf);
extern void CHAR_Print(char *buf, int len);
extern int socket_init(void);
extern int modbus_read(int addr, int slaveAddr, int len, uint16_t *data);
extern void mushu_to_list(unsigned int area_temp, unsigned short areaRate_temp, unsigned short depth_temp, unsigned short depthRate_temp, u32 work_length, unsigned short work_time);
extern void clean_gps_data(char *path);
extern void calAreaAndWight(char *p, unsigned int area_temp, unsigned short areaRate_temp, unsigned short depth_temp, unsigned short depthRate_temp, unsigned int work_length, unsigned short work_time);
extern void AndroidGpsProcess(double x,double y, int buttonStart, double bearing, double speed);
extern int minizip(int argc, char **argv);
extern void jniToJava(char *buf, unsigned int len);
extern void write_gps_info(const char *fmt, ...);
extern void write_gps_area_info(const char* fmt, ...);
extern void write_log_to_sdcard(char *path, const char *fmt, ...);
extern uint32_t GPRSDataSend(char *Senddata, int len, long usec, int read_len);
extern void addWaterMark(unsigned char*buf, int offset_h, int mFrameWidth, int mFrameHeight, char* str_date);
extern int unzip(const char * zipfilename, const char* filename_to_extract, const char *password, const char *dirname);
extern void argb2yuv420sp(unsigned char* src_p, unsigned char* alph,                                                                                            
                int width, int height,
                unsigned char* dest_y, unsigned char* dest_c);
extern void yuv420sp_blending(int bg_width, int bg_height, int left, unsigned int top, int fg_width, int fg_height,
                       unsigned char *bg_y, unsigned char *bg_c, unsigned char *fg_y, unsigned char *fg_c, unsigned char *alph);
extern void yuv420sp_blending_adjust_brightness(int bg_width, int bg_height, int left, int top, int fg_width, int fg_height,
                       unsigned char *bg_y, unsigned char *bg_c, unsigned char *fg_y, unsigned char *fg_c, unsigned char *alph,
                       int is_brightness);
extern void AT_CSCA( void );
extern int epoll_threadfd;
extern int yuv422_to_yuv420p(char* src, char *dest, int w, int h);
extern struct ring_buffer *ring_buf;
extern int read_offline_data(char *path, char *data);
extern void update_offline_data_tail(char *);
extern void sim800c_restart(void);
extern int open_camera();
extern int get_picture (unsigned char *data);
extern int close_camera();
extern unsigned long yuv420p_to_jpeg(char *yuv_input, unsigned char **jpeg_output, int image_width,int image_height, int quality);
extern unsigned int calDeep(void);
extern int write_led(int disp, int system_led, int gps_state, int gprs_state, int deep_state);
extern int open_led();
extern void close_led();
extern void UnicodeToUTF_8(char* pOut,wchar_t* pText);
extern int write_gpio(char *pin_name, int val);
extern int read_gpio(char *pin_name);
extern int open_gpio();
extern void close_gpio();
extern int remount_system(unsigned long flags);
extern void update_gprs_online();
extern int parseAsciiNetlinkMessage(char *buffer, int size);
extern int uevent_init();
extern int uevent_next_event(char* buffer, int buffer_length);
extern int checkExFile();
extern void ring_buffer_free(struct ring_buffer *ring_buf);
extern uint32_t ring_buffer_get(struct ring_buffer *ring_buf, void * buffer, uint32_t size);
extern uint32_t ring_buffer_put(struct ring_buffer *ring_buf, void *buffer, uint32_t size);
extern uint32_t ring_buffer_len(const struct ring_buffer *ring_buf);
extern struct ring_buffer* ring_buffer_init(void *buffer, uint32_t size, pthread_mutex_t *f_lock);
extern void SIM300HANGUPCALL();
extern void SetTerminalParameter(char *pTxtOfReceive);
extern int AnalysisToCallFromAndroid(char *p);
extern int initCmdDev();
extern void BlockRead (char *buf,int Length, int set);
extern void BlockWrite(char *buf,int Length, int set);
extern int openUart(char *path, int flags);
extern int set_baudrate(const int fd, const char *bautrate);
extern void closeUart(int fd);
extern void Tc35_Init(void);
extern void device_init(void);
extern void GetAuthenticationCode(void);
extern void GetCCID(char* pCcidstring);
extern void WriteComm( char *pData,int nLength);
extern int ReadComm( int nWaiteTime);
extern     int SendCmdToSim900A(char *cmd,char *ack,unsigned int waitFor_10ms);
extern void   deal_with_sms(void);
extern void   deal_with_phone(char *);
extern int  GPRSDealUnso();
extern int gsmReadMessageSingle(CMGStruct *pMsg,int smsno);
extern  int gsmSendMessage( CMGStruct* pSrc);
extern char *RemoveColon(char* pinput);
extern  u8 GetGsmCSQ(char * Buf);
extern int gsmString2Bytes( unsigned char* pSrc, unsigned char* pDst, int nSrcLength);
extern u16  get_prev_data(u8 staid,u8 endid);
extern u32 calculata_oil(u32 adval);
extern void    SaveSysRunPaga(u8 *psrc);
extern void GPRSHQS23Encode(char *Sendbuf );
extern void SMSPro(void);
extern void SIM300ANSWERCALL();
extern int CIPCLOSE(void);
extern int CIPSHUT(void);
extern int CheckCIPSTATUS(void);
extern void Delay10ms(int s);
extern void SetMux(void);
extern void SetMode();
extern  int CSTT();
extern int CIICR();
extern int CIFSR();
extern int CIPTCPSTART(char *IPbuf);
extern int GPRSLink(int LinkType);
extern unsigned int  TCPSTAT( void );
extern void Delay(unsigned int nTime);
extern int CIPSEND(char* pSrc,int len);
extern void variable_init(void);
extern void LoginAndAuthentication(void);
extern u8 SendAreaAndWeight(void);
extern void HEX_Print(char *buf, int len);
extern u8 GetGprsRSSI(void);
extern u8 locat_to_list(int, int);
extern u8 plus();
extern unsigned char  SIM300ATCheck();
extern void    patch_30s_msg(void);
extern void    read_data(void);
extern void ResponseForSetDeviceParameters(void);
extern void TRIG_LOW();
extern void TRIG_HIGH();
extern int  openUltra(void);
extern int  readUltra();
extern void TriggerUltrasonic(void);
extern int  GetDelayOfUltrasonic(void);
extern int CalDistanceFromTopToGrain(int count, unsigned int distance);
extern void LoadDistanceAndGetShrowGrainState(void);
extern void closeUltra();
extern void initCmdSocket(int fd);
extern void closeCmdSocket(int *fd);
extern void BlockInit();
extern void BlockClose();
extern int ctl_sim_power(char data);
extern void SIM300_PWROFF(void);
extern void SIM300_PWRON(void);
extern void ReportGrainHeightAndClearState(void);
extern void sleepMsec(long long msec);
extern void sleepUsec(long long usec);
extern int writeline (int, const char *s);
extern const char *readline(int);
extern void *handlerGpsAndCmd(void *arg);
extern int OfflineBlockRead(char *path, struct list_head *head, unsigned int data_size);
extern int OfflineBlockWrite(char *path, struct list_head *head);
extern void OfflineBlockInit(void);
extern void OfflineBlockClose(void); 
extern int lcd_power(int enable);
extern int gps_factory_test(void);
#define SIM_POWER_PATH "/sys/devices/platform/sim800c/sim800c_r_w"

#define COMMAND_REFUEL 1
#define COMMAND_SERVICE 1 << 1

#define HIGH_LEVEL 1
#define LOW_LEVEL 0
#define GRAIN_HALF_HEIGHT 800
#define SHROW_DOWN_HEIGHT 700

#define TRIGGER_PREIOD 500
//触发周期500ms
#define CALCULATION_PREIOD 6000
//计算周期5s
#define DISTANCE_BUFF_NUM 4

#define SOUND_SPEED 368
#define HALF_SOUND_SPEED SOUND_SPEED/2

//超声波最大测距能力：1500mm
#define MAX_DISTANCE 2000
#define MAX_DESCREASE_COUNTER 4
#define FILTER_NUM 10
#define SUCCESS 1
CMGStruct MY_SM_PARAM ;
CMGStruct MY_SM_PARAM_SMS[5] ;
#define  OIL_DATA_MAX_NUMBER 1500
#define  OIL_DATA_MAX_ADDRESS (OIL_DATA_MAX_NUMBER * 28)
#define SYSINFO_SET 512 // len sizeof(SysInf)
#define data_start_addr_set (I2C_EEPROM_OIL_START_ADDRESS + 2)

// 用户信息编码方式
#define GSM_7BIT  0
#define GSM_8BIT  4
#define GSM_ASC   4
#define GSM_UCS2  8
#define SM_PARAMLen 215
#define TRUE 1
#define FALSE 0
typedef  struct GPS
{
    unsigned char AnchorState;//定位状态
    float Latitude;  //维度
    float Longitude; //精度
    float NSpeed;  //速度
    unsigned int Date;
    unsigned int Time;
}GPS;
#define GPSLength  sizeof(GPS)

typedef  struct GPRSStruct
{
    char CMD[5];
    char Message[512];
}GPRSStruct;
GPS GPSInfor;
#pragma pack ()
typedef    struct _sysdatareg
{
    u8     trandsstartflag;
    u8       adcstartnum;
    u8     adcendnum;
    u16    trandskeeptime;
    u32    tandsovertime;
    u8     have_dec_trands;
    u8     have_add_trands;
    u8     sensestatus;
    u8     senseerror;
    u8     oilkeepflag;
    u8     runmode;
    u8     min1num;
    u8     min4_count;
    u8     t30flag;
    u8     addflag;
    u8     min10keep;
    u8     stealflag;
    u8     start_flag;
    u8     addoilendNum;
    u8     addoilendflag;
    u8     stealoilendNum;
    u8     stealoilendflag;
    u8     add_bit;
    u8     dec_bit;
    u8     deckeeptime;
    u8     starttimer;
    u16    startaddoilAD;
    u16    startstealoilAD;
    u16    endstealoilAD;
    u16    endaddoilAD;
    u16    low_mark2;
    u16    high_mark2;
    u16    low_val2;
    u16    high_val2;
    u16    threshold;

    u8     s30dec_bit;
    u8     s30steal_warn;

    u16    low_mark;
    u16    high_mark;
    u16    ad_base;
    u16    low_val;
    u16    high_val;
    u16    full_oil;
    u16    add_warn;
    u16    steal_warn;
    u16    now_oilval;
    u16    out_oilval;
    u16    last_addoil;
    u16    current_oilval;
    u16    trandsstartoil;
    u16    add_oil_L;
    u16    steal_oil_L;
    u32    gps_speed_sta;
    u32    dec_keep_flag;
    u32    add_keep_flag;
    u32    speed_keep_flag;
    u16    min12;
    u16    oilinflatedm;
    u32    diffkeeptime;
    u32    stealtime;
    u16    s30databuf[80];
    u16    stealflag2;
    u16    stealstartad2;
}_SYSDATAREG;
_SYSDATAREG   sysrundata;

typedef    struct _u1datareg
{
    u8     revsta;
    u8     datalength;
    u8     revlen;
    u8     revdata[32];
    u8     tempchknum;
    u8     revdatanum;
    u8     revdataflag;
    u8     comctrl;
}_U1DATAREG;
_U1DATAREG    u1data;
#define    normal_mode     0
#define    addoil_mode     1
#define    stealoil_mode   2


#define    NORMAL       normal_mode
#define    REFUEL     addoil_mode
#define    STEAL_OIL  stealoil_mode

#define   SetSysPaga       1
#define   OpenCom          2
#define   closeCom         3
#define   ClrProgram       4
#define   SetPassword      5
#define   ReadSysPaga      6
#define   Set30SPaga       7
#define   Read30sPaga      8

#define   SetSysPaga2      11
#define   ReadSysPaga2     12

#define   userreadcom      30
#define   usersetpaga      31
#define   userreadpaga     32
#define   readversion      33
typedef    struct _adcdatareg
{
    u8     adcount;
    u8     adc_num;
    u8     runmode;
    u8     min1num;
    u8     t30flag;
    u8     addoilendNum;
    u8     stealoilendNum;
    u16    startaddoilAD;
    u16    s30_counter;
    u16    s6_counter;
    u32    ADCdatasum[2];
    u16    min2ad;
    u16    adc_data[2][256];
    u16    data_6s[2][5];
    u16    lastadval;

}_ADCDATAREG;
_ADCDATAREG   adcdatastore;
_U1DATAREG    u1data;
typedef    struct _u4datareg
{
    u8     WaitAckn;
    u8     revsta;
    u8     revdata[16];
    u8     tempchknum;
    u8     revdatanum;
    u8     revdataflag;
    u8     read_nsensor;
    u8     sensor_noack_times[4];
    u8     sensor_error_flag[4];
    u16    nchdata[4];
}_U3DATAREG;
_U3DATAREG    u3msgdata;
typedef    struct _gpsdatareg
{
    u8     new_msg_flag;
    u8     gps_data[100];
    u8     min4_count;
    u8     rev_data_sta;
    u8     rev_data_num;
    u16    gps_rate[240];
    u16    startstealoilAD;
    u16    endstealoilAD;
}_GPSDATAREG;
#pragma pack (1)
struct Back_data
{
    u8 gps_flag;
    u8 Jing_bit;
    u8 Wei_bit;
    u8 Time_Year;
    u8 Time_Mon;
    u8 Time_Day;
    u8 Time_Hour;
    u8 Time_Minu;
    u8 Time_Secon;
    u8 oil_chang_flag;
    u16 Speed;
    u16 Jiao;
    u16 data_num;   //油量
    u16 oil_ad_valu;//AD值
    u16 oil_chang_valu; //增减差值
    u32 Wei;
    u32 Jing;

};
#define  OIL_DATA_MAX_NUMBER 1500
#endif
